﻿using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static B.MESUI.Login.WareHouseManage.WareHouseArea.CreateAreaForm;
using static B.MESUI.Login.WareHouseManage.WareHouseArea.WareHouseAreaForm;

namespace B.MESUI.Login.WareHouseManage.WareHouseArea
{
    public partial class UpdateAreaForm : DevExpress.XtraEditors.XtraForm
    {
        public UpdateAreaForm()
        {
            InitializeComponent();
        }
        public void SetEditData(WareHouseAreaEditModel model)
        {
            textEdit1.Text = model.areaid;
            textEdit4.Text = model.areaname;
            textEdit2.Text = model.areadesc;
            // 设置下拉框选中值
            gridLookUpEdit2.EditValue = model.warehouseid;

            // 存储 ID 以便保存时使用
            this.Tag = model.id;
        }
        private void Load_AreaEdit(object sender, EventArgs e)
        {
            LoadWarehousesAsync();
            
        }
        public class ApiResult
        {
            public List<WarehouseModel> ResultData { get; set; }
        }
        public async Task LoadWarehousesAsync()
        {
            using (var client = new HttpClient())
            {
                try
                {
                    var response = await client.GetAsync("http://39.103.49.30:9981/api/WareHouseDefinition/GetWarehouseDefinitionIdAndName");

                    if (response.IsSuccessStatusCode)
                    {
                        string json = await response.Content.ReadAsStringAsync();
                        var result = JsonConvert.DeserializeObject<ApiResult>(json);

                        // 绑定数据到 GridLookUpEdit
                        gridLookUpEdit2.Properties.DataSource = result.ResultData;
                        gridLookUpEdit2.Properties.ValueMember = "Id";
                        gridLookUpEdit2.Properties.DisplayMember = "WareHouseName";

                        // 配置视图 - 这是关键修复点！
                        // 获取或创建 GridView
                        GridView view = gridLookUpEdit2.Properties.View as GridView;
                        if (view == null)
                        {
                            view = new GridView();
                            gridLookUpEdit2.Properties.View = view;
                        }

                        // 清除现有列
                        view.Columns.Clear();

                        // 添加列：仓库名称
                        view.Columns.Add(new GridColumn()
                        {
                            FieldName = "WareHouseName",
                            Caption = "仓库名称",
                            Visible = true
                        });

                        // 添加列：仓库ID（可选）
                        view.Columns.Add(new GridColumn()
                        {
                            FieldName = "Id",
                            Caption = "仓库ID",
                            Visible = false // 隐藏ID列
                        });

                        // 设置最佳列宽
                        view.BestFitColumns();

                        // 默认选中第一个
                        if (result.ResultData.Count > 0)
                            gridLookUpEdit2.EditValue = null;
                    }
                    else
                    {
                        MessageBox.Show("无法加载仓库信息");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发生错误: {ex.Message}");
                }
            }
        }
        public class AreaModel
        {
            public string id { get; set; }
            public string areaid { get; set; }     // 区域编码
            public string areaname { get; set; }   // 区域名称
            public string warehouseid { get; set; }// 所属仓库ID
            public string areadesc { get; set; }   // 区域描述
        }

        

        private async void simpleButton1_Click_1(object sender, EventArgs e)
        {
            // 获取用户输入
            string areaid = textEdit1.Text.Trim();
            string areaname = textEdit4.Text.Trim();
            string warehouseid = gridLookUpEdit2.EditValue?.ToString();
            string areadesc = textEdit2.Text.Trim();

            // 非空校验
            if (string.IsNullOrEmpty(areaid))
            {
                MessageBox.Show("区域编码不能为空");
                return;
            }
            if (string.IsNullOrEmpty(areaname))
            {
                MessageBox.Show("区域名称不能为空");
                return;
            }
            if (string.IsNullOrEmpty(warehouseid))
            {
                MessageBox.Show("所属仓库不能为空");
                return;
            }
            if (string.IsNullOrEmpty(areadesc))
            {
                MessageBox.Show("区域描述不能为空");
                return;
            }

            // 构造请求体对象
            var model = new AreaModel
            {
                areaid = areaid,
                areaname = areaname,
                warehouseid = warehouseid,
                areadesc = areadesc,

                id = this.Tag?.ToString() // 从 Tag 中获取 ID
            };

            // 序列化为 JSON
            string jsonContent = JsonConvert.SerializeObject(model);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            // 发起 POST 请求
            using (var client = new HttpClient())
            {
                try
                {
                    var response = await client.PostAsync("http://39.103.49.30:9981/api/Area/UpdateAREAMODEL", content);

                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("保存成功！");
                        this.DialogResult = DialogResult.OK; // 设置对话框结果
                        this.Close(); // 关闭当前窗口
                    }
                    else
                    {
                        string errorText = await response.Content.ReadAsStringAsync();
                        MessageBox.Show($"保存失败: {errorText}");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发生错误: {ex.Message}");
                }
            }
        }
    }
}